package com.sk.waste.app.fragments

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.lc.smc.lib.views.pulllayout.SKPullRefresh
import com.lc.smc.lib.views.pulllayout.SKPullRefreshLayout
import com.sk.waste.app.R
import com.sk.waste.app.activitys.ShDetailActivity
import com.sk.waste.app.activitys.SyDetailActivity
import com.sk.waste.app.adapters.MarketAdapter
import com.sk.waste.app.adapters.MerchantAdapter
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseFragment
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.models.MaterialModel
import com.sk.waste.app.models.MerchantlModel
import com.sk.waste.app.utils.OkHttpUtil
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException
import java.util.Arrays

/**
 * 商家
 */
class MerchantFragment : BaseFragment() {

    private var ettSearch: EditText? = null
    private var bttSearch: Button? = null
    private var recyclerView: RecyclerView? = null
    private var pullRefreshLayout: SKPullRefreshLayout? = null

    private lateinit var mAdapter: MerchantAdapter
    private var merchantList = ArrayList<MerchantlModel>()

    private var searchStr = ""
    private var currentPage = 1
    val userinfo = MyApplication.instance.getUserInfo()

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.fragment_third)
        super.onCreate(savedInstanceState)
    }

    override fun findView() {
        ettSearch = findViewById(R.id.view_search_text) as EditText?
        bttSearch = findViewById(R.id.view_search_butt) as Button?
        recyclerView = findViewById(R.id.fg_merchant_recyclerview) as RecyclerView?
        pullRefreshLayout = findViewById(R.id.ac_swipe_refreshLayout) as SKPullRefreshLayout?
    }

    override fun setListener() {
        pullRefreshLayout!!.onStartListener = refreshListener
        pullRefreshLayout!!.onStartListener.onStartRefresh(pullRefreshLayout)

//        judgeVip()

        recyclerView!!.layoutManager = LinearLayoutManager(mContext)
        mAdapter = MerchantAdapter(requireActivity(), 1, merchantList, mOnItemClickListener)
        recyclerView!!.adapter = mAdapter

        bttSearch!!.setOnClickListener {
            merchantList.clear()
            currentPage = 1
            hideKeyboard()
            searchStr = ettSearch!!.text.toString()
            getMerchantList()
        }
        ettSearch!!.setOnEditorActionListener { v, actionId, event -> // 在这里处理搜 索逻辑
            // 返回 true 表示你已经处理了这个事件
            merchantList.clear()
            currentPage = 1
            searchStr = ettSearch!!.text.toString()
            getMerchantList()
            true
        }

    }

    private val mOnItemClickListener = object : LCInterface.LcCallBack {
        override fun callBack(vararg args: Any?) {
            val position = args[0] as Int
            val intent = Intent(mContext, ShDetailActivity::class.java)
            intent.putExtra("extral_merchant",merchantList[position])
            startActivity(intent)
        }

    }

    private val refreshListener = object : SKPullRefresh.OnStartListener {
        override fun onStartRefresh(p0: SKPullRefresh?) {
            currentPage = 1
            getMerchantList()
        }

        override fun onStartLoadmore(p0: SKPullRefresh?) {
            if (userinfo!!.isVip()) {
                currentPage++
                getMerchantList()
            } else {
                currentPage = 1
                pullRefreshLayout!!.loadmoreSuccess()
            }
        }
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 商户列表
     *  @param url
     */
    private fun getMerchantList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_SHLIST
        val token = LCSPUtil[mContext!!, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("pageSize", AppConfig.PAGE_SIZE)
        params.put("pageNo", currentPage)
        params.put("realName", searchStr)
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                freshOrLoadFaild()
                LCBaseUtil.showToast(context, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONObject("data")
                    val rows = data.getJSONArray("records")
                    if (currentPage == 1) {
                        merchantList.clear()
                    }
                    if (success) {
                        activity!!.runOnUiThread {
                            if (rows.length() == 0) {
                                showToastLong("暂无数据...")
                            }
                            fresOrLoadSuccess(rows.length())
                            for (index in 0 until rows.length()) {
                                val item = MerchantlModel().apply { getModelInfo(rows.getJSONObject(index)) }
                                merchantList.add(item)
                            }
//                            judgeVip()
                            mAdapter.notifyDataSetChanged()
                        }
                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        freshOrLoadFaild()
                        LCBaseUtil.showToast(context, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    freshOrLoadFaild()
                    LCBaseUtil.showToast(context, "获取失败，" + e.message)
                    Log.e("LCLOG_ERROR", e.toString())
                }
            }
        })
    }

//    private fun judgeVip()
//    {
//        val userinfo = MyApplication.instance.getUserInfo()
//        if (userinfo?.isVip() == true) {
//            pullRefreshLayout!!.isLoadmoreable = true;
//        } else {
//            pullRefreshLayout!!.isLoadmoreable = false;
//        }
//    }

    private fun fresOrLoadSuccess(rows: Int) {
        if (1 == currentPage) { // 刷新
            pullRefreshLayout!!.refreshSuccess()
            merchantList.clear()
        } else {
            pullRefreshLayout!!.loadmoreSuccess()
        }
        if (rows == AppConfig.PAGE_SIZE) {
            pullRefreshLayout!!.isLoadmoreable = true
        } else {
            pullRefreshLayout!!.isLoadmoreable = false
        }
    }

    private fun freshOrLoadFaild() {
        activity?.runOnUiThread {
            if (currentPage == 1) {
    //            pullRefreshLayout.stopRefresh()
    //                pullRefreshLayout.refreshSuccess();
                pullRefreshLayout!!.refreshFailed();
            } else {
    //                pullRefreshLayout.loadmoreSuccess()
                pullRefreshLayout!!.loadmoreFailed()
            }
        }
    }


}